<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
class User extends BaseController
{
   public function index(){
   	//调用模型层实现业务逻辑
   	$users=Db::query("select * from users order by uid desc");
   	$this->assign("list",$users);
   	//dump($users);exit;
   	//调用视图层把从模型层获取的数据显示出来
   	
   	return $this->fetch();
   }
   public function delete($id){
   	//删除用户之前先删除用户头像
   	//find方法和unlink方法
   	if(db("users")->delete($id)){
   		$this->success("删除成功");
   			
   	}else $this->error("删除失败");

   }
   
   public function add(){
   		$uname=input('param.uname');
		$num=Db::name('users')->where("uname='$uname'")->count();
    	if($num>0)
    	  $this->error("该用户名已经存在");
		//准备数据:非空的，没默认值的，非自增长，都要赋值
		  $file = request()->file('pic');
    	// 移动到框架应用根目录/public/uploads/ 目录下
    	
      	$info = $file->rule('uniqid')->move(ROOT_PATH.'public'.DS.'static'.DS.'admin'.DS.'images');
        $pic = $info->getSaveName();
		//准备数据:非空的，没默认值的，非自增长，都要赋值
		$data=[
			'uname'=>$uname,
			'password'=>md5(input('param.password')),
			'pic'=>$pic,
			'gender'=>input('param.gender'),
			'birthdate'=>input('param.birthdate'),
			'email'=>input('param.email')
		];
		if(Db::name("users")->insert($data)){
			$this->success("添加用户成功");
    	}
    	else $this->error("添加用户失败");
	}

public function edit(){
		$uid=input("param.uid");
		$user=Db::name("users")->find($uid);
		echo json_encode($user);
	}
	
	public function update(){
		$uname=input('param.uname');
		$num=Db::name('users')->where("uname='$uname'")->count();
    	if($num>0)
    	  $this->error("该用户名已经存在");
		//准备数据:非空的，没默认值的，非自增长，都要赋值
		  $file = request()->file('pic');
    	// 移动到框架应用根目录/public/uploads/ 目录下  	
      	$info = $file->validate(['size'=>3000000,'ext'=>'jpg,png,gif'])->rule('uniqid')->move(ROOT_PATH.'public'.DS.'static'.DS.'admin'.DS.'images');
        $pic = $info->getSaveName();
		$data=[
			'uid'=>input('param.uid'),
			'uname'=>$uname,
			'password'=>md5(input('param.password')),
			'pic'=>$pic,
			'gender'=>input('param.gender'),
			'birthdate'=>input('param.birthdate'),
			'email'=>input('param.email')
			];
		if(Db::name("users")->update($data)){
			$this->success("修改用户成功");
		}else{
			$this->error("修改用户失败");
		}

	}
}